package com.xiacherensheng.demo.basejava.classinfo;

import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.net.URLClassLoader;

public class CustomClassLoader extends ClassLoader {
    private String path;

    public CustomClassLoader(String basePath) {
        this.path = basePath;
    }

    public Class<?> loadClass(String name) throws ClassNotFoundException{
        if (name.startsWith("com.xiacherensheng")){
            return findClass(name);
        } else {
            try {
                return super.loadClass(name);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

        throw new ClassNotFoundException();

    }

    public Class<?> findClass(String name) {
        byte[] classess = new byte[0];
        try {
            classess = getClassByte(name);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return defineClass(name, classess, 0, classess.length);
    }

    public byte[] getClassByte(String name) throws Exception {
        String classFileName = name.replace(".", File.separator) + ".class";
        FileInputStream inputStream = new FileInputStream(path + File.separator + classFileName);
        byte[] results = new byte[inputStream.available()];
        inputStream.read(results);
        return results;
    }


}
